package top.gohigh.springboot.service.impl;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.gohigh.springboot.dao.RoleDao;
import top.gohigh.springboot.dao.UserDao;
import top.gohigh.springboot.model.Role;
import top.gohigh.springboot.model.User;
import top.gohigh.springboot.model.UserGroup;
import top.gohigh.springboot.service.RoleService;
import top.gohigh.springboot.service.UserGroupService;
import top.gohigh.springboot.service.UserService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserGroupService userGroupService;

    @Override
    public User add(String username, String pwd, Long group) {

        String salt=new SecureRandomNumberGenerator().nextBytes().toHex();
        String ciphertext=new Md5Hash(pwd,salt,3).toString();

        User user=new User();
        user.setUserName(username);
        user.setPassword(ciphertext);
        user.setSalt(salt);
        user.setGroup(userGroupService.findById(group));
        userDao.save(user);
        return  user;
    }

    @Override
    public User addRole(Long uid, Long rid) {
        Role role=roleService.getById(rid);

        User user=getById(uid);

        List<Role> roles= user.getRoles();
        if(roles==null){
            roles=new ArrayList<>();
            user.setRoles(roles);
        }
        roles.add(role);
        userDao.save(user);
        return user;
    }

    @Override
    public User getById(Long id) {
        return userDao.findById(id).get();
    }

    @Override
    public User getByName(String name) {
        return userDao.findUserByUserName(name);
    }

    @Override
    public User getByNameAndPwd(String username, String pwd) {
        return userDao.findUserByUserNameAndPassword(username,pwd);
    }


}
